import * as crypto from 'crypto';
const path = require('path');
const moment = require("moment");
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
const {AGCClient, CredentialParser} = require("@hw-agconnect/common-server");
import { user } from './db/user'
import { mc_meeting } from './db/mc_meeting'
import { mc_meeting_user_relation } from './db/mc_meeting_user_relation'
// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientCN", "CN");
const agcClient = AGCClient.getInstance("clientCN");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);
//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

function generateRandomNumber() {
  let randomNum = Math.floor(Math.random() * 1000000);
  return randomNum.toString().padStart(6, '0');
}

let myHandler = async function (event, context, callback, logger) {
  const { phone, uid } = event.body ? JSON.parse(event.body) : event
  // 查询是否有当前用户
  let userCloudDBZoneQuery = null
  if (phone) {
    userCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(user).equalTo('phone', phone)
  } else {
    userCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(user).equalTo('id', uid)
  }
  const respUser = await mCloudDBZone.executeQuery(userCloudDBZoneQuery);
  const data = respUser.getSnapshotObjects()
  let userInfo = null
  if (data.length) {
    userInfo = {
      ...data[0],
      meetingNum: 0,
      relationNum: 0
      // workNum: 0, // 作品数
      // workShareNum: 0, // 贡献值
      // fansNum: 0 // 粉丝值
    }
    const tempCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(mc_meeting).equalTo('createBy', uid)
    const respTemp = await mCloudDBZone.executeQuery(tempCloudDBZoneQuery);
    const workData = respTemp.getSnapshotObjects()
    userInfo.meetingNum = workData.length
    let cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(mc_meeting_user_relation).equalTo('userId', uid)
    const respFollow = await mCloudDBZone.executeQuery(cloudDBZoneQuery);
    const followData = respFollow.getSnapshotObjects()
    userInfo.relationNum = followData.length || 0
  } else {
    userInfo = {
      id: uid,
      phone,
      name: '',
      downNum: 0,
      avatarUrl: '',
      bgWallUrl: '',
      sex: 2,
      signature: '',
      password: 'mc123456',
      createTime: moment().format("YYYY/MM/DD HH:mm:ss")
    }
    const bookInfo = clouddb.CloudDBZoneGenericObject.build('user')
    for (const key in userInfo) {
      bookInfo.addFieldValue(key, userInfo[key]);
    }
    await mCloudDBZone.executeUpsert(bookInfo)
  }
  delete userInfo.password
  let res = new context.HTTPResponse({
    code: 200,
    msg: '用戶信息',
    data: userInfo
  }, {
    "faas-content-type": "json"
  }, "application/json", "200");
  callback(res);
};

export { myHandler }
